<template>
  <div class="container">
    <el-card>
      <el-row>
      <el-col :span="6">
        <el-menu  class="el-menu-vertical-demo chat-menu" @select="selectUser">
          <el-menu-item :index="contact" v-for="contact in userList" :key="contact">
            <el-avatar class="avatar" :src="contact.image"></el-avatar>
            <span style="margin-left: 6px;">{{ contact.name }}</span>
          </el-menu-item>
        </el-menu>
      </el-col>
      <el-col :span="18">
        <div class="chat-content" ref="chatContentRef">
          <template v-if="chatList && chatList.length">
            <div v-for="(chat, index) in chatList" class="message-box"
              :class="{ 'right-message': chat.user.uid === userInfo?.uid }" :key="index">
              <div v-if="chat.user.uid !== userInfo?.uid" class="user">
                  <div class="info">
                    <el-avatar class="avatar" :src="chat.user.image"></el-avatar>
                    <div>
                      <div class="name">{{ chat.user.name }}</div>
                      <div class="time">{{ chat.create_time }}</div>
                    </div>
                  </div>
                  <div class="message">
                    <div class="block">{{ chat.info }}</div>
                  </div>
              </div>
              <div v-else class="user">
                <div class="message">
                  <div class="block">{{ chat.info }}</div>
                </div>
                <div class="info">
                  <div>
                    <div class="name">{{ chat.user.name }}</div>
                    <div class="time">{{ chat.create_time }}</div>
                  </div>
                  <el-avatar class="avatar" :src="chat.user.image"></el-avatar>
                </div>
              </div>
            </div>
          </template>
          <div v-else class="empty"> 没有消息 </div>
        </div>
        <div class="chat-bottom">
          <el-input v-model="chatMsg" class="chat-input" placeholder="请输入内容" />
          <el-button class="chat-btn" type="primary" @click="()=>sendMsg(chatUserId,houseId)">发送</el-button>
        </div>
      </el-col>
    </el-row>
    </el-card>
  </div>
</template>

<script>
import { onMounted, onUnmounted, ref, reactive,watch ,nextTick } from 'vue'
import io from 'socket.io-client'
import { send, getChatsApi, getUsers} from '/@/api/chat/chat.ts'
import { useUserStore } from '/@/store/modules/user'
import { createLocalStorage } from '/@/utils/cache'
import { LOCALE_KEY } from '/@/enums/cacheEnum'
import { useRefs } from '/@/hooks/core/useRefs'
import { useRouter } from 'vue-router'
const avatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'

export default {
  name: 'chat',
  setup() {
    const userStore = useUserStore()
    const { currentRoute, push ,replace} = useRouter()
    const chatContentRef = ref(null);
    let chatList = ref([
      {
        user: {
          id: 1,
          uid: '1',
          name: '111',
          password: '15',
          type: 2,
          image: '15',
          rmb: 15,
          create_time: '2023-12-31 23:10:38',
        },
      },
    ])
    const chatMsg = ref('')
    let userList = ref([])
    let toUserInfo = ref({})
    const userInfo = userStore.getUserInfo
    let websocket = null
    let intervalID = null
    const heartInfo = "i am a heart"
    let heartIndex = 10
    const chatUserId = currentRoute.value.query.chatUserId
    const houseId = currentRoute.value.query.house_id

    const currentUserId = ref("")
    onMounted(() => {
      fetchWebSocket()
      setSocketInterval()
      initSendUserInfo().then(res=>{
        fetchGetUsers()
      })
    })

    onUnmounted(() => {
      unMounted()
    })

    watch(toUserInfo, (newValue, oldValue) => { //直接监听
      getChats()
    });

    // watch(() => currentRoute.value,(newVal, oldVal) => { 
    //   const chatUserId = newVal.query.chatUserId
    //   const currentChatUser = userList.value.find(item=>item.uid == chatUserId)
    //   if(currentChatUser){
    //     toUserInfo.value = currentChatUser
    //   }
    // },{ immediate: true });

    const fetchWebSocket = () => {
      const ls = createLocalStorage()
      const userInfo = ls.get(LOCALE_KEY+'bb_user_info')
      websocket = new WebSocket(`ws://localhost:23423/websocket?user_id=${userInfo?.uid}`)
      websocket.onopen = onOpen
      websocket.onmessage = onMessage
      websocket.onerror = onError
      websocket.onclose = onClose
      heartIndex = 10
    }

    const unMounted = () => {
      websocketClose()
      if (intervalID == null) {
        return
      }
      clearInterval(intervalID);
      intervalID = null
    }

    const refreshWebSocket = () => {
      if (websocket == null || heartIndex <= 0) {
        //reset socket
        fetchWebSocket()
        return
      }
      heartIndex--
    }

    const setSocketInterval = () => {
      if (intervalID) {
          clearInterval(intervalID);
      }
      intervalID = setInterval(refreshWebSocket, 1000, new Date())
    }

    const initSendUserInfo = () => {

      if (!chatUserId) {
        console.log("chatUserId none:" + chatUserId)
        return new Promise(res=>res())
      }

      console.log("chatUserId:" + chatUserId)

      return sendMsg(chatUserId, houseId)
   }

    const fetchGetUsers = () =>{
      const ls = createLocalStorage()
      const userInfo = ls.get(LOCALE_KEY+'bb_user_info')
      getUsers(userInfo.uid).then(res=>{
        userList.value = res.msg
        const currentChatUser = userList.value.find(item=>item.uid == chatUserId || item.id == currentUserId.value)
        if(currentChatUser){
          toUserInfo.value = currentChatUser
        }else{
          toUserInfo.value = res.msg[0]
        }
      })
    }
    const onOpen = (e) => {
      console.log(e, 'onOpen')
    }
    const onMessage = (messageEvent) => {
      console.log(messageEvent, 'onMessage')
      if (messageEvent.data == heartInfo) {
        //reset heart
        heartIndex = 10
        return
      }
      const data = JSON.parse(messageEvent.data)
      chatList.value.push(data)
      fetchGetUsers()
      if (websocket == null) {
        return
      }
      websocket.send(messageEvent.data)
    }
    const onError = (e) => {
      console.log(e, 'onError')
    }
    const onClose = (e) => {
      console.log(e, 'onClose')
    }
    const selectUser = (user) => {
      toUserInfo.value = user
      currentUserId.value = user.id;
    }
    const sendMsg = (chatUserId, houseId) => {
      // TODO
      const data = {
        id: Number(),
        name: userInfo.name,
        uid: userInfo?.uid,
        user_id: userInfo?.uid,
        chat_id: chatUserId ? chatUserId : toUserInfo.value?.uid,
        info: houseId ? houseId : chatMsg.value,
        state: houseId ? 10000 : 0,
        create_time: new Date(),
        user:userInfo
      }
      return send(data).then((res) => {
        console.log(res)
        chatList.value.push(data)
      })
      chatMsg.value = ''
    }
    const websocketClose = () => {
      if (websocket != null) {
          websocket.close()
      }
    }

    const getChats = () => {
      const data = {
        "user_id": userInfo?.uid,
        "chat_id": toUserInfo.value?.uid,
        "page": 0
      }
      getChatsApi(data).then((res) => {
        chatList.value = res.msg.reverse();
        nextTick(() => {
          let scrollElem = chatContentRef.value;
          scrollElem.scrollTo({ top: scrollElem.scrollHeight });
        });
      })
    }
    return {
      chatMsg,
      chatList,
      userList,
      userInfo,
      toUserInfo,
      sendMsg,
      selectUser,
      chatContentRef,
      chatUserId,
    }
  },
}
</script>

<style lang="scss" scoped>
@mixin flex($align) {
  display: flex;
  align-items: $align;
}

.container {
  padding: 0 24px;
  margin: 24px auto 10px
}

.chat-bottom {
  @include flex(center);
  margin: 10px;
  width: 100%;
}

.chat-menu{
  height: 70vh;
  overflow-y: scroll;
}

.chat-content {
  width: 100%;
  height: 70vh;
  padding: 10px;
  margin: 0 10px;
  border: 1px solid #ddd;
  box-sizing: border-box;
  overflow-y: scroll;
  overflow-x: hidden;

  .message-box {
    margin-bottom: 10px;

    .message {
      margin-left: 42px;
      border-radius: 4px;
      box-sizing: border-box;
      margin-top: 5px;

      .block {
        display: inline-block;
        font-size: 14px;
        line-height: 1.5;
        border-radius: 4px;
        padding: 8px;
        background-color: #eee;
      }
    }

    .user {
      .avatar {
        width: 32px;
        height: 32px;
        margin-right: 10px;
      }

      @include flex(center);
    }

    .info {
      @include flex(center);
      font-size: 12px;
      color: #999;

      .name {
        margin-right: 10px;
      }
    }

    &.right-message {
      display: flex;
      text-align: right;
      justify-content: flex-end;

      .message {
        // margin-left: auto;
      }
      .info{
        margin-left: 10px;
      }

      .user {
        .name {
          margin-right: 0px;
          margin-left: 10px;
        }
        .avatar {
          width: 32px;
          height: 32px;
          margin-left: 10px;
        }

      }

      .avatar {
        margin-right: 0px;
        margin-left: 10px;
      }
    }
  }
}

.empty {
  font-size: 14px;
  padding: 50px 0;
  text-align: center;
}

.chat-input {
  &:deep(.el-input__inner) {
    border-top-right-radius: 0;
    border-top-left-radius: 0;
    border-bottom-right-radius: 0;
  }
}

.chat-btn {
  border-top-left-radius: 0;
  border-top-right-radius: 0;
  border-bottom-left-radius: 0;
}
</style>
